/**
 * Created by commy on 2015/4/30.
 */
var express = require('express'),
    app = module.exports = express(),
    bodyParser = require('body-parser'),
    redis = require('./redis'),
    md5 = require('js-md5'),
    connect = require('./mongodb'),
    merge = require('utils-merge'),
    eventProxy = require('eventproxy'),
    validator = require('validator');


// create application/json parser
var jsonParser = require('./jsparser');



app.post('/member/create',jsonParser,function(req,res,next){
    var ep = new eventProxy();
    ep.fail(next);
    var content = req.body.content;
    var keys = Object.keys(content);
    for(var i in keys){
        content[keys[i]+'_optime'] = req.body.optime;  //给每一个成员的每个数据附上一个最新的操作时间
    }
    connect(function(db){

        //每个成员都有一个id
        db.collection('size_table').findOneAndUpdate({user_id:req.userid},{
            $inc:{
                genid:1
            }
        },{upsert:true,returnOriginal:false},ep.done(function(result){
            console.log(result);
            db.collection('size_table').updateOne({user_id:req.userid},{
                $push:{
                    member_list:merge(req.body.content,{id:result.value.genid ,optime:req.body.optime}) //给每个成员的数据附上最新的操作时间
                },
                $set:{
                    optime:req.body.optime //给该用户的成员列表附上最新的操作时间
                }
            },ep.done(function(result){
                res.status(200).json({state:'success'});
            }));

        }));

    })
});

app.post('/member/delete',jsonParser,function(req,res,next){
    var ep = new eventProxy();
    ep.fail(next);
    connect(function(db){
        db.collection('size_table').findOne({user_id:req.userid}, ep.done(function(result) {
            // console.log(result);
            var finded = false;
            for(var i in result.member_list){
                if(result.member_list[i].id==req.body.id){
                    if(result.member_list[i].optime < req.body.optime){
                        db.collection('size_table').updateOne({user_id:req.userid},
                            {
                                $pull:{member_list:{id:req.body.id}}
                            },
                            ep.done(function(result){
                                res.status(200).json({state:'success'});
                            }));
                    }else{
                        res.status(503).json({state:'error'});
                    }
                    finded = true;
                    break;
                }
            }
            if(!finded){
                res.status(200).json({state:'success'});
            }
        }));
    });
});

app.get('/member/list',function(req,res,next){
    var ep = new eventProxy();
    ep.fail(next);
    connect(function(db){
        db.collection('size_table').findOne({user_id:req.userid},ep.done(function(result){
            res.status(200).json(result);
        }));
    });
});

app.post('/member/change',jsonParser,function(req,res,next){
    var ep = new eventProxy();
    ep.fail(next);
    connect(function(db){

        db.collection('size_table').findOne({user_id:req.userid},ep.done(function(result){
            var member_list = result.member_list;
            var getMember =  function(id){
                for(var j in member_list){
                    if(member_list[j].id==id){
                        return member_list[j];
                    }
                }
                return false;
            };

            for(var i in req.body){
                var operator = req.body[i];
                var member = getMember(operator.id);
                console.log(member);
                if(member && member[operator.field+'_optime'] <operator.optime){
                    member[operator.field] = operator.value;
                    member[operator.field+'_optime'] = operator.optime;
                    member.optime = parseInt(Date.now()/1000);
                }
            }

            db.collection('size_table').updateOne(
                {user_id:req.userid},
                {$set:{member_list:member_list}},
                ep.done(function(result){
                    // console.log(result);
                    res.status(200).json({state:'success'});
                })
            )

        }));
    });
});

app.get('/update/first',function(req,res,next){
    var ep = new eventProxy();
    ep.fail(next);
    connect(function(db){

        db.collection('size_table').findOne({user_id:req.userid},ep.done(function(result){
            var member_list = result.member_list;
            var md5_member_list = [];
            for(var i in member_list){
                md5_member_list[i] = {
                    id:member_list[i].id,
                    md5:md5(JSON.stringify(member_list[i]))
                }
            }

            res.status(200).json({
                md5_member_list:md5_member_list
            });

        }));
    });
});
